package com.dai.zhenfujin.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.MotionEvent;

import com.dai.zhenfujin.R;


/**
 * 根据宽高比例自动计算高度ImageView
 * Created by HMY on 2016/4/21.
 */
public class RatioImageView2 extends RoundImageView {

    /**
     * 宽高比例
     */
    private float mRatio = 0f;
    private final Matrix matrix = new Matrix();
    private Bitmap bmp;
    private Paint bmpPaint;
    private Path path = new Path();
    private RectF rectF = new RectF();

    public RatioImageView2(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public RatioImageView2(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RatioImageView);

        mRatio = typedArray.getFloat(R.styleable.RatioImageView_ratio, 0f);
        typedArray.recycle();
        initViews();
    }

    public RatioImageView2(Context context) {
        super(context);
        initViews();
    }

    private void initViews() {
        bmpPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);
        bmpPaint.setStyle(Paint.Style.FILL);
        bmpPaint.setAntiAlias(true);

//        ULog.d("比例：" + ratio + ",参考边：" + (referEdge == 1 ? "宽" : "高")
//            + "，弧度：" + radius);
    }

    /**
     * 设置ImageView的宽高比
     *
     * @param ratio
     */
    public void setRatio(float ratio) {
        mRatio = ratio;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = MeasureSpec.getSize(widthMeasureSpec);
        if (mRatio != 0) {
            float height = width / mRatio;
            heightMeasureSpec = MeasureSpec.makeMeasureSpec((int) height, MeasureSpec.EXACTLY);
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                Drawable drawable = getDrawable();
                if (drawable != null) {
                    drawable.mutate().setColorFilter(Color.GRAY,
                            PorterDuff.Mode.MULTIPLY);
                }
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
                Drawable drawableUp = getDrawable();
                if (drawableUp != null) {
                    drawableUp.mutate().clearColorFilter();
                }
                break;
        }

        return super.onTouchEvent(event);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        rectF.top = 0;
        rectF.left = 0;
        rectF.right = getWidth(); // 宽度
        rectF.bottom = getHeight(); // 高度
        setBitmapShader();
    }

    @Override
    public void setImageResource(int resId) {
        super.setImageResource(resId);
        bmp = getBitmapFromDrawable(getDrawable());
        setBitmapShader();
    }

    @Override
    public void setImageDrawable(Drawable drawable) {
        super.setImageDrawable(drawable);
        bmp = getBitmapFromDrawable(drawable);
        setBitmapShader();
    }

    @Override
    public void setScaleType(ScaleType scaleType) {
        if (mRatio > 0 && scaleType != ScaleType.CENTER_CROP) {
            throw new IllegalArgumentException("设置圆弧图片的时候，缩放类型最好是：CENTER_CROP");
        }
    }


    @Override
    protected void onDraw(Canvas canvas) {
        if (bmp != null) {
            path.reset();
            path.addRoundRect(rectF, mRatio, mRatio, Path.Direction.CW);
            canvas.drawPath(path, bmpPaint);
        }
    }


    private void setBitmapShader() {
        if (bmpPaint == null) {
            return;
        }
        if (bmp == null) {
            invalidate();
            return;
        }
        BitmapShader bmpShader = new BitmapShader(bmp, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        bmpPaint.setShader(bmpShader);

        matrix.set(null);//固定为CENTER_CROP
        // 缩放
        float scale = Math.max(getWidth() * 1f / bmp.getWidth(), getHeight() * 1f / bmp.getHeight());
        //居中
        float dx = (getWidth() - bmp.getWidth() * scale) / 2;
        float dy = (getHeight() - bmp.getHeight() * scale) / 2;
        matrix.setScale(scale, scale);
        matrix.postTranslate(dx, dy);
        bmpShader.setLocalMatrix(matrix);
        invalidate();//刷新
    }

    /**
     * drawable转换成bitmap
     */
    private Bitmap getBitmapFromDrawable(Drawable drawable) {
        if (drawable == null) {
            return null;
        }
        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        }
        try {
            Bitmap bitmap;
            if (drawable instanceof ColorDrawable) {
                bitmap = Bitmap.createBitmap(2, 2, Bitmap.Config.ARGB_8888);
            } else {
                bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
            }
            Canvas canvas = new Canvas(bitmap);
            drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
            drawable.draw(canvas);
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private int dp2px(float value) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, getResources().getDisplayMetrics());
    }
}
